package com.youlu.campus.component;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.youlu.campus.base.exception.BusinessException;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class QiniuUtil {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private QiniuConfig qiniuConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String uploadFileByUrl(String url, String fileName,String type, boolean check, List<String> checkList){
        InputStream inputStream = null;
        try {
            URL uri = new URL(url);
            inputStream = uri.openStream();
            String key = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            // false:如果用户真实头像就是这个，则不校验,true表示校验
            if(check && CollectionUtils.isNotEmpty(checkList)) {
                ByteArrayOutputStream outputStream = getByteArrayOutputStream(inputStream);
                byte[] bytes = outputStream.toByteArray();
                String m = MD5(new String(bytes,"UTF-8"));
                if(m == null || (checkList.contains(m))){
                    return "1";
                }
                inputStream = new ByteArrayInputStream(bytes);
            }
            if(StringUtils.isNotBlank(fileName)){
                fileName = type + key + fileName;
            }else{
                fileName = type + key + System.currentTimeMillis();
            }
            this.uploadFile(inputStream,fileName);
            String domain = qiniuConfig.getDomainOfBucket();
            return domain + "/" + fileName;
        } catch (Exception e) {
            log.error("uploadFileByUrl error",e);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error("inputStream close error",e);
                }
            }
        }
        return "2";
    }


    public static ByteArrayOutputStream getByteArrayOutputStream(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        byte[] var4 = array;
        int var5 = array.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            byte item = var4[var6];
            sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
        }

        return sb.toString().toUpperCase();
    }

    public String uploadFileWithFileName(InputStream inputStream, String fileName) {
        log.info(":>>> 上传文件开始。。。 {}", fileName);
        String url = qiniuConfig.getDomainOfBucket();
        fileName = System.currentTimeMillis() + fileName;
        try {
            //上传到七牛
            this.uploadFile(inputStream, fileName);
            url = url + "/" + fileName;
        } catch (IOException e) {
            log.error("<<<<<<<<<<<上传文件失败:{}", e);
            throw new BusinessException("文件上传失败！");
        }

        log.info(":>>> 结束 {}", url);
        return url;
    }

    /**
     * 七牛流文件上传
     *
     * @param inputStream
     * @return
     * @throws QiniuException
     */
    public String uploadFile(InputStream inputStream, String key) throws QiniuException {
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        // ...生成上传凭证，然后准备上传
        String upToken = getQiniuToken();
        if (StringUtils.isBlank(upToken)) {
            upToken = generateQiniuToken();
        }
        log.info(":>>> 七牛token:{}", upToken);

        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = uploadManager.put(inputStream, key, upToken, null, null);
            retry++;
        }
        //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info(":>>> 七牛云上传文件响应信息:{}", response.bodyString());
        return key;
    }

    /**
     * 七牛流文件上传
     *
     * @param inputStream
     * @return
     * @throws QiniuException
     */
    public String resumableUploadFile(InputStream inputStream, String key) throws Exception {
        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        // 指定分片上传版本
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        // 设置分片上传并发，1：采用同步上传；大于1：采用并发上传
        cfg.resumableUploadMaxConcurrentTaskCount = 2;
        // ...其他参数参考类注释
        //设置断点续传文件进度保存目录
        log.info("tmpdir:{}",System.getenv("java.io.tmpdir"));
        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), qiniuConfig.getBucket()).toString();
        log.info("localdir:{}",localTempDir);
        FileRecorder fileRecorder = new FileRecorder(localTempDir);
        UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
        // ...生成上传凭证，然后准备上传
        String upToken = getQiniuToken();
        if (StringUtils.isBlank(upToken)) {
            upToken = generateQiniuToken();
        }
        log.info(":>>> 七牛token:{}", upToken);
        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = uploadManager.put(inputStream, key, upToken, null, null);
            retry++;
        }
        //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info(":>>> 七牛云上传文件响应信息:{}", response.bodyString());
        return key;
    }


    //链接url下载图片
    public String downloadPicture(String imgUrl, String filePath) {
        URL url = null;
        try {
            url = new URL(imgUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String imageName = filePath + System.currentTimeMillis();
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            return imageName;
        } catch (MalformedURLException e) {
            log.error(":<<< downloadPicture1 error:{}", e);
        } catch (IOException e) {
            log.error(":<<< downloadPicture2 error:{}", e);
        }
        return "";
    }

    public String getQiniuToken() {
        String redisQiniuTokenKey = qiniuConfig.getRedisQiniuTokenKey();
        String qiniuToken = "";
        try {
            qiniuToken = redisTemplate.opsForValue().get(redisQiniuTokenKey);
        } catch (Exception e) {
            log.error(":<<< getQiniuToken error:{}", e);
        }

        return qiniuToken;
    }

    public String generateQiniuToken() {
        String accessKey = qiniuConfig.getAccessKey();
        String secretKey = qiniuConfig.getSecretKey();
        String bucket = qiniuConfig.getBucket();
        String redisQiniuTokenKey = qiniuConfig.getRedisQiniuTokenKey();

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        log.info("七牛云token生成成功 :{}", upToken);
        try {
            redisTemplate.opsForValue().set(redisQiniuTokenKey, upToken,3603, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("七牛云token存储错误 error:{}", e);
        }

        return upToken;
    }
}
